import CmdMethodsMap from './cmd.methods.map.js';

class CmdMethods {
	constructor() {
		this.initializeCommands();
	}

	/**
	 * 发送命令的通用方法
	 * @param {Object} options - 包含 Socket 和 cmd 的对象
	 * @param {Object} data - 额外的参数
	 */
	sendCommand({
		Socket,
		cmd,
	}, data) {
		const params = {
			cmd,
			...data
		};
		Socket.send(params);
	}

/**
 * 动态生成命令方法
 */
initializeCommands() {
	Object.keys(CmdMethodsMap).forEach(cmdName => {
		this[cmdName] = (options, data) => {
			console.log(`options:`,options);
			const {
				params,
			} = CmdMethodsMap[cmdName];
			const filteredData = params.reduce((acc, param) => {
				if (data && data.hasOwnProperty(param)) {
					acc[param] = data[param];
				}
				return acc;
			}, {});
				this.sendCommand(options, {
					...filteredData,
					...data
				});

		};
	});
}

/**
 * 根据 cmd 值调用对应的方法
 * @param {Object} options - 包含 Socket 和 cmd 的对象
 * @param {Object} data - 额外的参数
 */
callCommandByCmdMethods(options, data) {
	const commandName = Object.keys(CmdMethodsMap).find(key => CmdMethodsMap[key].cmd === options.cmd);
	if (commandName) {
		this[commandName](options, data);
	} else {
		console.error(`Command with cmd ${options.cmd} not found.请在 cmd.methods.map.js 文件添加函数配置`);
	}
}

/**
 * 动态添加命令配置
 * @param {string} cmdName - 命令名称
 * @param {Object} config - 命令配置对象，包含 cmd 和 params [参数]string可以为空数组
 * @example addCmdMethodsConfig('getInfos',{cdm:99 , params: ['user_id']})
 */
addCmdMethodsConfig(cmdName, config) {
	const defineComponent = {
		cmd: Symbol(),
		params: []
	}
	if (CmdMethodsMap[cmdName]) {
		console.warn(`Command ${cmdName} already exists. Overwriting existing configuration.`);
	}
	// 检查 cmd 值是否已经存在
	const existingCmd = Object.values(CmdMethodsMap).find(cmdConfig => cmdConfig.cmd === config.cmd);
	if (existingCmd) {
		console.error(`Command with cmd ${config.cmd} already exists.`);
		return;
	}

	CmdMethodsMap[cmdName] = {
		...defineComponent,
		...config
	};
	this.initializeCommands(); // 重新初始化命令方法
}

}
// 初始化命令方法
// CmdMethods.prototype.initializeCommands();

export default CmdMethods;